package auth

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"go-proxy/config"
	"net/http"
	"strings"
)

type JwtAuth struct {
}

func NewJwtAuth() *JwtAuth {
	return &JwtAuth{}
}

func (j *JwtAuth) checkAuth(w http.ResponseWriter, r *http.Request, auth *config.Auth) bool {
	if len(auth.Jwt.Secret) <= 0 {
		return false
	}

	authHeader := r.Header.Get("Authorization")
	if authHeader == "" {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return false
	}

	// 解析 Authorization 头
	authParts := strings.SplitN(authHeader, " ", 2)
	if len(authParts) != 2 || authParts[0] != "Bearer" {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return false
	}

	// 解析并验证 token
	token, err := jwt.Parse(authParts[1], func(token *jwt.Token) (interface{}, error) {
		// 确认签名方法
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(auth.Jwt.Secret), nil
	})

	if err != nil || token == nil || !token.Valid {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return false
	}

	return true
}
